--- 模块功能：MQTT客户端数据接收处理
-- @author openLuat
-- @module mqtt.mqttInMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)
require "logGenerator"
require "nvm"

-- 参数配置文件初始化
nvm.init("config.lua", true)
-- 变量初始化
local slen, errInfo, sysTime, clientNo, orgId = string.len, "", "",
                                                nvm.get("info")[1],
                                                nvm.get("info")[4]

-- 设备是否在重启列表判断
local function clientNoInClientsOrNot(clientsGet, restartDeviceCmd)
    local resultCom, isCmdOrNot, restartList = false, false, {}
    print("clientsGet:", clientsGet[1])
    for i = 1, #clientsGet do
        if clientNo == clientsGet[i] then
            log.info("clientNo匹配!!")
            resultCom = true
        end
    end
    restartList = restartDeviceCmd:split(" ")
    if #restartList > 0 then
        for i = 1, #restartList, 1 do
            log.info("orgId", orgId, "restartList[i]:", restartList[i])
            if clientNo == restartList[i] then -- 设备号匹配
                log.info("设备号匹配")
                resultCom = true
            elseif orgId == restartList[i] then
                log.info("单位id匹配") -- 单位id匹配
                resultCom = true
            elseif "all" == restartList[i] then -- 所有设备匹配
                log.info("所有设备重启")
                resultCom = true
            elseif "restart" == restartList[i] then -- 启动指令匹配
                log.info("启动指令匹配")
                isCmdOrNot = true
            end
        end
    end
    return resultCom, isCmdOrNot
end
--- MQTT客户端数据接收处理
-- @param mqttRClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttInMsg.proc(mqttRClient)
function proc(mqttRClient)
    local result, data, receiveMsg, base64DecodeMsg, aesDecryptMsg, todo,
          clients
    local restartDeviceIs, isCmd = false, false
    while true do
        sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d",
                                os.date("*t").year, os.date("*t").month,
                                os.date("*t").day, os.date("*t").hour,
                                os.date("*t").min, os.date("*t").sec)
        result, data = mqttRClient:receive(60000, "APP_SOCKET_SEND_DATA")
        errInfo = ""
        -- 接收到数据
        if result then
            receiveMsg = data.payload
            log.info("receiveMsg1232:", receiveMsg)
            base64DecodeMsg = crypto.base64_decode(receiveMsg, slen(receiveMsg))
            aesDecryptMsg = crypto.aes_decrypt("ECB", "PKCS5", base64DecodeMsg,
                                               "keson-123abcdefg")
            log.info("receiveMsgCMD", aesDecryptMsg)
            local tjsondata, resultMqtt, errinfo = json.decode(aesDecryptMsg)
            if resultMqtt and type(tjsondata) == "table" then
                if "guard" == data.topic then
                    todo = tjsondata["todo"]
                    log.info("clients", tjsondata["clients"])
                    if tjsondata["clients"] then
                        clients = tjsondata["clients"]
                    end
                    if "terminal" == todo then
                        if tjsondata["guardCmd"] then
                            restartDeviceIs, isCmd =
                                clientNoInClientsOrNot(clients, tjsondata["cmd"])
                            log.info("restartDeviceIs", restartDeviceIs,
                                     "isCmd", isCmd)
                            if restartDeviceIs then
                                if isCmd then
                                    sys.restart("守护程序重启设备！")
                                end
                            end
                        end
                    end
                end
            else
                errInfo = errInfo .. "[" .. sysTime .. "]" ..
                              "[json.decode error:]" .. errinfo .. "\n"
                logGenerator.generateLogTask(errInfo, "log")
                print("json.decode error", errinfo)
            end
        else
            break
        end
    end
    log.info("MQTT INMSG QU TASK  RESULT", result, "MQTT INMSG QU TASK DATA",
             data)
    return result or data == "timeout" or data == "APP_SOCKET_SEND_DATA"
end
